package org.itworks.biodev.gui.panels;

import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.sql.SQLException;
import java.util.*;

import javax.swing.*;
import javax.swing.table.DefaultTableModel;

import org.itworks.biodev.gui.*;
import org.itworks.biodev.model.*;
import org.itworks.helpers.MVCNotification;
import org.itworks.helpers.gui.ButtonColumn;

public class SalesPanelView extends JPanel implements Observer {

	/* Observer constants */
	public static final int FILL_SALES_TABLE = 1;
	public static final int FILL_SALE_DETAILS_TABLE = 2;
	public static final int FILL_SALE_ID_LABEL = 3;
	
	private static final long serialVersionUID = 7238571876907538880L;
	private static SalesPanelView salesPanelView = null;
	private SalesPanelControler controler = null;
	private MainWindowView parent = null;
	
    private javax.swing.JButton createNewSaleButton;
    private javax.swing.JButton deleteSelectedSaleButton;
    
	private JLabel customerNameSalesFilterLabel;
    private JTextField customerNameSalesFilterTextField;
    private JButton filterSalesButton;
    private JLabel idMeetingSalesFilterLabel;
    private JTextField idMeetingSalesFilterTextField;
    private JButton idSaleReachButton;
    private JLabel idSaleReachLabel;
    private JTextField idSaleReachTextField;
    private JScrollPane salesListScrollPane;
    private JTable salesTable;
    private JLabel salesTitleLabel;
	
	public SalesPanelView(MainWindowView parent, SalesPanelControler controler) {
		this.parent = parent;
		this.controler = controler;
		this.controler.getModel().addObserver(this);
		
		initControls();
		initHandlers();
		
		this.controler.viewLoaded();
	}
	
	


	private void initControls() {
		salesTitleLabel = new JLabel();
        customerNameSalesFilterLabel = new JLabel();
        customerNameSalesFilterTextField = new JTextField();
        idMeetingSalesFilterLabel = new JLabel();
        idMeetingSalesFilterTextField = new JTextField();
        filterSalesButton = new JButton();
        idSaleReachLabel = new JLabel();
        idSaleReachTextField = new JTextField();
        idSaleReachButton = new JButton();
        salesListScrollPane = new JScrollPane();
        salesTable = new JTable();
        
        createNewSaleButton = new javax.swing.JButton();
        deleteSelectedSaleButton = new javax.swing.JButton();


        salesTitleLabel.setFont(new java.awt.Font("Trebuchet MS", 1, 18));
        salesTitleLabel.setText("Ventes");

        customerNameSalesFilterLabel.setText("Nom client :");

        idMeetingSalesFilterLabel.setText("Identifiant reunion :");

        filterSalesButton.setText("Filtrer");

        idSaleReachLabel.setText("Identifiant vente :");

        idSaleReachButton.setText("Atteindre");
        
        createNewSaleButton.setText("Creer une vente");
        deleteSelectedSaleButton.setText("Suppression multiple");

        salesTable.setModel(new javax.swing.table.DefaultTableModel(
            new Object [][] {

            },
            new String [] {
                "Identifiant", "Produit vendu", "Quantite", "Client", "Identifiant reunion"
            }
        ) {
			/**
			 * 
			 */
			private static final long serialVersionUID = 1446332441295611353L;
			
			boolean[] canEdit = new boolean [] {
                false, false, false, false, false
            };

            public boolean isCellEditable(int rowIndex, int columnIndex) {
                return canEdit [columnIndex];
            }
        });
        salesListScrollPane.setViewportView(salesTable);

        javax.swing.GroupLayout layout = new javax.swing.GroupLayout(this);
        this.setLayout(layout);
        layout.setHorizontalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGap(0, 1100, Short.MAX_VALUE)
            .addGroup(layout.createSequentialGroup()
                .addContainerGap()
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                    .addComponent(salesListScrollPane, javax.swing.GroupLayout.DEFAULT_SIZE, 1080, Short.MAX_VALUE)
                    .addComponent(salesTitleLabel)
                    .addGroup(layout.createSequentialGroup()
                        .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.TRAILING)
                            .addComponent(customerNameSalesFilterLabel)
                            .addComponent(idSaleReachLabel))
                        .addGap(36, 36, 36)
                        .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                            .addComponent(customerNameSalesFilterTextField, javax.swing.GroupLayout.PREFERRED_SIZE, 101, javax.swing.GroupLayout.PREFERRED_SIZE)
                            .addComponent(idSaleReachTextField, javax.swing.GroupLayout.PREFERRED_SIZE, 67, javax.swing.GroupLayout.PREFERRED_SIZE))
                        .addGap(18, 18, 18)
                        .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                            .addGroup(layout.createSequentialGroup()
                                .addComponent(idMeetingSalesFilterLabel)
                                .addGap(18, 18, 18)
                                .addComponent(idMeetingSalesFilterTextField, javax.swing.GroupLayout.PREFERRED_SIZE, 59, javax.swing.GroupLayout.PREFERRED_SIZE)
                                .addGap(18, 18, 18)
                                .addComponent(filterSalesButton))
                            .addComponent(idSaleReachButton))))
                            .addComponent(deleteSelectedSaleButton)
                            .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED, 20, Short.MAX_VALUE)
                            .addComponent(createNewSaleButton)
                .addContainerGap())
        );
        layout.setVerticalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGap(0, 734, Short.MAX_VALUE)
            .addGroup(layout.createSequentialGroup()
                .addContainerGap()
                .addComponent(salesTitleLabel)
                .addGap(18, 18, 18)
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(filterSalesButton)
                    .addComponent(deleteSelectedSaleButton)
                    .addComponent(createNewSaleButton)
                    .addComponent(idMeetingSalesFilterTextField, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                    .addComponent(idMeetingSalesFilterLabel)
                    .addComponent(customerNameSalesFilterTextField, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                    .addComponent(customerNameSalesFilterLabel))
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(idSaleReachLabel)
                    .addComponent(idSaleReachTextField, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                    .addComponent(idSaleReachButton)
                    )
                .addGap(18, 18, 18)
                .addComponent(salesListScrollPane, javax.swing.GroupLayout.DEFAULT_SIZE, 603, Short.MAX_VALUE)
                .addContainerGap())
        );
	}
	
	private void initHandlers() {
		this.createNewSaleButton.addActionListener(new ActionListener() {

			@Override
			public void actionPerformed(ActionEvent actionEvent) {
				// TODO Auto-generated method stub
				try {
					controler.createNewSaleButtonActionPerformed(actionEvent);
				} catch (Exception e) {
					// TODO Auto-generated catch block
					e.printStackTrace();
				}
				
			}
			
		});
		
		this.deleteSelectedSaleButton.addActionListener(new ActionListener() {
			
			
			public void actionPerformed(ActionEvent actionEvent) {
				Vector<Integer> selectedIndexes = new Vector<Integer>();
				/* Pour chaque ligne */
				for(int i = 0; i < salesTable.getRowCount(); i++) {
					/* Si la case est coch�e */
					if(salesTable.getValueAt(i, 5).toString().equals("true")) {
						selectedIndexes.add(Integer.parseInt(salesTable.getValueAt(i, 0).toString()));
					}
				}
				controler.deleteSelectedSalesButtonActionPerformed(actionEvent, selectedIndexes);
			}
		});
	}
	

	@SuppressWarnings("unchecked")
	@Override
	public void update(Observable srcObject, Object object) {
		// TODO Auto-generated method stub
		MVCNotification notification = (MVCNotification)object;
		int reason = notification.getReason();
		
		switch(reason) {
		case FILL_SALES_TABLE:
			// todo.
			try {
				fillSalesTable( (Vector<Sale>)notification.getObject() );
			} catch (Exception e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
			break;
		case FILL_SALE_DETAILS_TABLE:
			try {
				//fillSaleDetailsTable((Vector<ProductSale>)notification.getObject());
				//productsListTable.setVisible(true);
				//totalLabel.setVisible(true);
				//totalTextField.setVisible(true);
			} catch (Exception e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
			break;
		case FILL_SALE_ID_LABEL:
			try {
				//orderDetailsTitleLabel.setText((String)notification.getObject());
				//orderDetailsTitleLabel.setVisible(true);
			} catch (Exception e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
			break;
		}
	}
	
	public static SalesPanelView getInstance(MainWindowView parent) {
		if(salesPanelView == null) {
			salesPanelView = new SalesPanelView(parent, new SalesPanelControler( new SalesPanelModel()));
		}
		return salesPanelView;
	}
	
	private void fillSaleDetailsTable(Vector<ProductSale> products) throws Exception {
		DefaultTableModel model = new javax.swing.table.DefaultTableModel(
	               new Object [][] {
	               },
	               new String [] {
	                   "Produit", "Quantite", "Prix unitaire", "Prix total"
	               }
	           ) {
	               Class[] types = new Class [] {
	               		java.lang.String.class, java.lang.Integer.class, java.lang.Float.class, java.lang.Float.class
	               };
	               boolean[] canEdit = new boolean [] {
	                   false, false, false, false
	               };

	               public Class getColumnClass(int columnIndex) {
	                   return types [columnIndex];
	               }

	               public boolean isCellEditable(int rowIndex, int columnIndex) {
	                   return canEdit [columnIndex];
	               }
	           };
	          // productsListTable.setModel(model);
				
		   		// Remplissage du tableau productsListTable	et du total de la commande
		   		Float totalPriceOrder=(float) 0;
				
				for (int i=0 ; i<products.size() ; i++) 
				{
					Vector<Object> rowData = new Vector<Object>();
					ProductSale currentProdutSale = products.get(i);
					rowData.add(products.get(i).getProduct().getLabel());
					rowData.add(currentProdutSale.getQuantity());
					rowData.add(currentProdutSale.getProduct().getPrice());
					Float totalPrice = currentProdutSale.getProduct().getPrice() * currentProdutSale.getQuantity();
					rowData.add(totalPrice);
					
					model.addRow(rowData);
					
					totalPriceOrder = totalPriceOrder + totalPrice;
				}	
				//this.totalTextField.setText(totalPriceOrder.toString());
		}
	
	private void fillSalesTable(Vector<Sale> sales) throws InstantiationException, IllegalAccessException, ClassNotFoundException, SQLException {
		DefaultTableModel model = new javax.swing.table.DefaultTableModel(
            new Object [][] {

            },
            new String [] {
                "Identifiant", "Date", "Quantite totale", "Prix total", "Modifier", "Annuler" // A checker
            }
        ) {
			
            /**
			 * 
			 */
			private static final long serialVersionUID = -758028855472131221L;
			
			Class[] types = new Class [] {
	                java.lang.Integer.class, java.lang.String.class, java.lang.Integer.class, java.lang.Float.class, java.lang.String.class, Boolean.class
	            };

	            public Class getColumnClass(int columnIndex) {
	                return types [columnIndex];
	            }
	            
			boolean[] canEdit = new boolean [] {
                false, false, false, false, true, true
            };

            public boolean isCellEditable(int rowIndex, int columnIndex) {
                return canEdit [columnIndex];
            }
	        
		};
		
		salesTable.setModel(model);
		
		for(Sale s : sales) {
			Vector<Object> rowData = new Vector<Object>();
			rowData.add(s.getId());
			rowData.add(s.getDate().toLocaleString());
			rowData.add(s.getTotalQuantity());
			rowData.add(s.getTotalPrice());
			rowData.add("Modifier");
			new ButtonColumn(salesTable, new AbstractAction() {

				/**
				 * 
				 */
				private static final long serialVersionUID = 5911305847353251182L;

				@Override
				public void actionPerformed(ActionEvent actionEvent) {
					// TODO Auto-generated method stub
					int selectedIndex = salesTable.getSelectedRow();
					controler.buttonColumnSalesActionPerformed(actionEvent, selectedIndex);
				}
				
			}, 4);
			rowData.add(new Boolean(false));
			model.addRow(rowData);
		}	
	}

}
